/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.isystem.autpart.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.isystem.autpart.beans.TAlmacen;
import org.isystem.autpart.beans.TSucursal;
import org.isystem.autpart.dao.DAO;
import org.isystem.autpart.util.idNew;
import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.Validator;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.bind.validator.AbstractValidator;

/**
 *
 * @author miguel-lap
 */
public class ManagerAdmAlmacen {
    
    private static final long serialVersionUID = 1L;
    private List<TAlmacen> almacenes = new LinkedList<TAlmacen>();
    private List<TSucursal> sucursales = new LinkedList<TSucursal>();
    private TAlmacen almacen = new TAlmacen();
    private TAlmacen almacenSelected = new TAlmacen();
    private TSucursal sucursalSelected = new TSucursal();
    private DAO dao = new DAO();
    private boolean verSave;
    private boolean mostrarAdd;
    private String saveLabel;
    private String buscar;
    private String val="";
    private Session s;
    
    //validators
    
    //validation messages
    Map<String, String> validationMessages = new HashMap<String,String>();
    
    @Init
    public void init(){
        System.out.println("Inicia AdminAlmacen");
        s = dao.getSession();
//        s.beginTransaction();
        actualizaListaAlmacen(s, "");
        mostrarAdd = false;
    }
    
    //Validators
    public Validator getFormValidator(){
        System.out.println("validator all");
        return new AbstractValidator() {
//            private HashMap validationMessages;

            public void validate(ValidationContext ctx) {
// Consultar si es persona natural o juridica
                String val = (String)ctx.getProperties("denominacion")[0].getValue();
                System.out.println("denominacion "  + val);
//                ValidationMessages vmsgs = (ValidationMessages) ctx.getValidatorArg("vmsgs");
//                validationMessages.put("usuarioTextBox", "value1 error");
//                ctx.setInvalid(); // mark invalid
//                ValidationMessages vmsgs = ((BinderCtrl)ctx.getBindContext().getBinder()).getValidationMessages();
//                addInvalidMessage(ctx, "usuario", "value1 error");
//                System.out.println("111");
//                ctx.getBindContext().getBinder().notifyChange(validationMessages, "usuarioTextBox");
//                if(invalidCondition01(val)){
//                    addInvalidMessage(ctx, "fkey1", "value1 error");
//                }
//                val = (String)ctx.getProperties("value2")[0].getValue();
//                if(invalidCondition02(val)){
//                    addInvalidMessage(ctx, "fkey2", "value2 error");
//                }
//                val = (String)ctx.getProperties("value3")[0].getValue();
//                if(invalidCondition03(val)){
//                    addInvalidMessage(ctx, "fkey3", "value3 error");
//                }
//                ctx.getBindContext().getBinder().notifyChange(validationMessages, "usuarioTextBox");
                
                
            }
        };
    }
    
    // botones
    @Command
    @NotifyChange({"verSave","almacen","mostrarAdd","saveLabel","sucursales","val", "sucursalSelected"})
    public void onClickadd() {
        System.out.println("click en agregar");
        almacen = new TAlmacen();
        almacen.setEstado("A");
        almacen.setTSucursal(new TSucursal());
        sucursalSelected = new TSucursal();
        val="";
//        Session s =dao.getSession();
//        s.beginTransaction();
        actualizaListaSucursales(s,"");
//        s.close();
        mostrarAdd = true;
        verSave = true;
        saveLabel ="Guardar";
    }
    
    @Command
    @NotifyChange({"almacenes", "buscar"})
    public void onClickSearch() {
        System.out.println("click search");
//        Session s = dao.getSession();
//        s.beginTransaction();
        actualizaListaAlmacen(s," where a.denominacion like '%"+buscar+"%'");
//        s.close();
    }
    
    @NotifyChange({"almacen","verSave","almacenes","val"})
    @Command()
    public void guardar() {
        System.out.println("guardar");
        //Asignacion de IDs
        if (saveLabel.equals("Guardar")) {
            //Asignacion de IDs
            almacen.setId(idNew.id());
        } else {
            if ((val.equals("")) && (almacen.getTSucursal() == null)){
                almacen.setTSucursal(null);
            }
        }
        almacen.setTSucursal(sucursalSelected);
//        Session s = dao.getSession();
        Transaction tr = s.beginTransaction();
        tr.begin();
        dao.persist(s,almacen);
        tr.commit();
        verSave = false;
        actualizaListaAlmacen(s, "");
//        s.close();
        System.out.println("fin guarda");
        return;
    }
    
    @NotifyChange({"verSave","almacen","mostrarAdd","saveLabel","sucursales", "val", "sucursalSelected"})
    @Command()
    public void edita(@BindingParam("alm") TAlmacen al ) {
        System.out.println("editar");
        verSave = true;
        almacen = new TAlmacen();
//        Session s = dao.getSession();
//        s.beginTransaction();
        almacen = (TAlmacen) dao.load(s, TAlmacen.class, al.getId()+"");
        almacen.setTSucursal((TSucursal) dao.load(s, TSucursal.class, almacen.getTSucursal().getId()+""));
        val="";
        actualizaListaSucursales(s, "");
        sucursalSelected = almacen.getTSucursal();
//        s.close();
        mostrarAdd = true;
        saveLabel = "Modificar";
        
    }
    
    @NotifyChange({"almacen","mostrarAdd","saveLabel","almacenes"})
    @Command()
    public void elimina(@BindingParam("alm") TAlmacen al ) {
        System.out.println("eliminar");
        almacen = al;
//        Session s = dao.getSession();
        Transaction tr = s.beginTransaction();
        tr.begin();
        dao.delete(s, almacen);
        tr.commit();
        mostrarAdd = false;
        actualizaListaAlmacen(s, "");
//        s.close();
    }
    
    // Change Selected
    @NotifyChange({"almacen","verSave","mostrarAdd","sucursales","almacenSelected","val"})
    @Command()
    public void selecciona() {
        System.out.println("Selecciona almacen");
        verSave = false;
        almacen = new TAlmacen();
        sucursales = new LinkedList<TSucursal>();
        val = "";
//        Session s = dao.getSession();
//        s.beginTransaction();
        actualizaListaSucursales(s, "");
//        s.close();
        almacen = almacenSelected;
        sucursalSelected = almacen.getTSucursal();
        mostrarAdd = true;
    }
    
    
    @Command()
    public void selecSucursal() {
        System.out.println("Selecciona Sucursal");
    }

    
    // Metodos
    private void actualizaListaAlmacen(Session s, String sql) {
        almacenes.clear();
        almacenes = dao.findAll(s,"from TAlmacen a" + sql);
    }
    
    private void actualizaListaSucursales(Session s, String sql) {
//        List <TSucursal> sus = new LinkedList<TSucursal>();
//        sus.clear();
        sucursales.clear();
//        sus = dao.findAll("from TSucursal s" + sql);
        sucursales = dao.findAll(s, "from TSucursal s" + sql);
//        for (TSucursal tSucursal : sus) {
//            if (tSucursal instanceof HibernateProxy) {
//                sucursales.add((TSucursal) ((HibernateProxy) tSucursal).getHibernateLazyInitializer().getImplementation());
//             }
//        }
    }

    public List<TAlmacen> getAlmacenes() {
        return almacenes;
    }

    public void setAlmacenes(List<TAlmacen> almacenes) {
        this.almacenes = almacenes;
    }

    public List<TSucursal> getSucursales() {
        return sucursales;
    }

    public void setSucursales(List<TSucursal> sucursales) {
        this.sucursales = sucursales;
    }

    public TAlmacen getAlmacen() {
        return almacen;
    }

    public void setAlmacen(TAlmacen almacen) {
        this.almacen = almacen;
    }

    public TAlmacen getAlmacenSelected() {
        return almacenSelected;
    }

    public void setAlmacenSelected(TAlmacen almacenSelected) {
        this.almacenSelected = almacenSelected;
    }

    public boolean isVerSave() {
        return verSave;
    }

    public void setVerSave(boolean verSave) {
        this.verSave = verSave;
    }

    public boolean isMostrarAdd() {
        return mostrarAdd;
    }

    public void setMostrarAdd(boolean mostrarAdd) {
        this.mostrarAdd = mostrarAdd;
    }

    public String getSaveLabel() {
        return saveLabel;
    }

    public void setSaveLabel(String saveLabel) {
        this.saveLabel = saveLabel;
    }

    public String getBuscar() {
        return buscar;
    }

    public void setBuscar(String buscar) {
        this.buscar = buscar;
    }

    public String getVal() {
        return val;
    }

    public void setVal(String val) {
        this.val = val;
    }

    public Map<String, String> getValidationMessages() {
        return validationMessages;
    }

    public void setValidationMessages(Map<String, String> validationMessages) {
        this.validationMessages = validationMessages;
    }

    public TSucursal getSucursalSelected() {
        return sucursalSelected;
    }

    public void setSucursalSelected(TSucursal sucursalSelected) {
        this.sucursalSelected = sucursalSelected;
    }

    
}
